package com.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bean.User;
import com.dao.UserDao;
import com.utils.MD5Util;

/**
 * Servlet Filter implementation class CodeFilter
 * 	登录过滤器
 */
@WebFilter("/pre/*")
public class LoginFilter implements Filter {
	private UserDao userDao = new UserDao();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		//转换类型
		HttpServletRequest request=(HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse)res;

		//设置输出流
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();

		//定义布尔值和变量，判断用户名和密码是否存在
		boolean flag = true;
		int n = 0;

		//获取session对象
		HttpSession session = request.getSession(true);
		//判断是否登录
		User login = (User)session.getAttribute("user");

		if (login != null) {
			chain.doFilter(request, response);
			flag = false;
		}

		//获取Cookie
		Cookie[] cookies=request.getCookies();
		//判断Cookie是否为空
		if (flag) {
			if (cookies != null) {
				//遍历数据
				for (int i = 0; i < cookies.length; i++) {
					Cookie cookie=cookies[i];
					//判断名称是否等于login
					if (cookie.getName().equals("login")) {
						//获取值,分割字符串
						String[] str = cookie.getValue()==null?null:cookie.getValue().split(":");

						//判断用户名和密码是否正确
						User user = userDao.LoginFlag(new User(str[0], MD5Util.MD5(str[1])));
						if ((str != null) && (user != null)) {
							//设置加密前的密码
							user.setPws(str[1]);
							//设置会话
							request.getSession().setAttribute("user",user);

							chain.doFilter(request, response);
							n = 1;
							break;
						}else {
							n = 1;
							//没有登录
							out.println("<script>alert('您没有权限，请重新登录');location.href='../login.jsp';</script>");
							break;
						}
					}
				}

				//判断是否找到用户名和密码
				if (n == 0) {
					out.println("<script>alert('您没有权限，请重新登录');location.href='../login.jsp';</script>");
				}
			}else {
				out.println("<script>alert('您没有权限，请重新登录');location.href='../login.jsp';</script>");
			}
		}
		//关闭
		out.flush();
		out.close();
	}

	@Override
	public void destroy() {

	}
}


